<template>
  <div class="bg-white rounded-lg shadow-md p-6">
    <!-- 用户统计模块 -->
    <div class="mb-8">
      <div class="flex justify-between items-center mb-4">
        <h3 class="font-semibold text-gray-800">用户统计</h3>
        <div class="flex space-x-2">
          <a-radio-group v-model="timeRange"
                         size="small"
                         @change="handleChange">
            <a-radio-button value="day">今日</a-radio-button>
            <a-radio-button value="week">本周</a-radio-button>
            <a-radio-button value="month">本月</a-radio-button>
          </a-radio-group>
        </div>
      </div>

      <div class="flex space-x-4">
        <!-- 在线用户卡片 -->
        <div class="flex-1">
          <div class="text-center">
            <p class="text-sm text-gray-500">在线用户</p>
            <p class="text-3xl font-bold text-gray-800 mt-1">{{ onlineUserCount }}</p>
            <p class="text-xs text-green-500 mt-1">
              <Icon type="arrow-up" /> 较昨日 {{ onlineUserGrowth }}
            </p>
          </div>
          <div class="mt-4 h-32">
            <div ref="onlineChartRef"
                 class="w-full h-full"></div>
          </div>
        </div>

        <div class="w-px bg-gray-200 my-2"></div>

        <!-- 活跃用户卡片 -->
        <div class="flex-1">
          <div class="text-center">
            <p class="text-sm text-gray-500">活跃用户</p>
            <p class="text-3xl font-bold text-gray-800 mt-1">{{ activeUserCount }}</p>
            <p class="text-xs text-green-500 mt-1">
              <Icon type="arrow-up" /> 较昨日 {{ activeUserGrowth }}
            </p>
          </div>
          <div class="mt-4 h-32">
            <div ref="activeChartRef"
                 class="w-full h-full"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户来源分布模块 -->
    <div class="bg-white rounded-lg shadow-md p-6">
      <div class="flex justify-between items-center mb-4">
        <h3 class="font-semibold text-gray-800">用户来源分布</h3>
        <div class="text-sm text-gray-500">
          <a-button type="link"
                    size="small"
                    @click="handleExport">
            <Icon type="download" /> 导出数据
          </a-button>
        </div>
      </div>

      <div class="flex flex-col md:flex-row space-y-6 md:space-y-0 md:space-x-8">
        <!-- 左侧饼图 -->
        <div class="md:w-1/2 h-64">
          <div ref="pieChartRef"
               class="w-full h-full"></div>
        </div>

        <!-- 右侧数据列表 -->
        <div class="md:w-1/2 flex flex-col justify-start space-y-3">
          <SourceDistributionItem v-for="(item, index) in sourceData"
                                  :key="index"
                                  :name="item.name"
                                  :value="item.value"
                                  :color="item.color" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import SourceDistributionItem from './SourceDistributionItem.vue';

// 接收父组件传入的时间范围
const props = defineProps({
  userTimeRange: { type: String, default: 'day' },
});

const emits = defineEmits(['timeRangeChange']);

// 状态管理
const timeRange = ref(props.userTimeRange);
const onlineChartRef = ref(null);
const activeChartRef = ref(null);
const pieChartRef = ref(null);

// 用户统计数据
const onlineUserCount = ref(186);
const activeUserCount = ref(842);
const onlineUserGrowth = ref('+12');
const activeUserGrowth = ref('+43');

// 地球科学相关大学用户来源数据
const sourceData = ref([
  { name: '吉林大学', value: '22.4%', color: '#1890FF' },
  { name: '中国地质大学（武汉）', value: '20%', color: '#2FC25C' },
  { name: '中国地质大学（北京）', value: '16%', color: '#FAAD14' },
  { name: '中国地质科学院地球物理与地球化学研究所', value: '12%', color: '#722ED1' },
  { name: '中国地质调查局航遥中心', value: '9.6%', color: '#13C2C2' },
  { name: '中国矿业大学', value: '12%', color: '#52C41A' },
  { name: '长安大学', value: '8%', color: '#F5222D' },
]);

// 时间范围变更处理
const handleChange = (e: any) => {
  timeRange.value = e.target.value;
  emits('timeRangeChange', e.target.value);
  updateCharts(); // 切换时间范围时更新图表
};

// 初始化所有图表
onMounted(() => {
  initCharts();
});

// 监听时间范围变化，更新图表
watch(timeRange, () => {
  updateCharts();
});

// 初始化所有图表
function initCharts() {
  if (onlineChartRef.value && activeChartRef.value && pieChartRef.value) {
    // 初始化在线用户图表
    const onlineChart = echarts.init(onlineChartRef.value);
    onlineChart.setOption(getChartOptions('在线用户', '#1890FF'));

    // 初始化活跃用户图表
    const activeChart = echarts.init(activeChartRef.value);
    activeChart.setOption(getChartOptions('活跃用户', '#2FC25B'));

    // 初始化来源分布饼图
    const pieChart = echarts.init(pieChartRef.value);
    pieChart.setOption(getPieChartOptions());

    // 监听窗口大小变化，调整所有图表
    window.addEventListener('resize', () => {
      onlineChart.resize();
      activeChart.resize();
      pieChart.resize();
    });
  }
}

// 更新图表数据
function updateCharts() {
  // 模拟不同时间范围的数据
  const isDay = timeRange.value === 'day';
  const isWeek = timeRange.value === 'week';

  // 更新统计数字
  if (isDay) {
    onlineUserCount.value = 186;
    activeUserCount.value = 842;
    onlineUserGrowth.value = '+12';
    activeUserGrowth.value = '+43';
  } else if (isWeek) {
    onlineUserCount.value = 1254;
    activeUserCount.value = 5842;
    onlineUserGrowth.value = '+234';
    activeUserGrowth.value = '+843';
  } else {
    onlineUserCount.value = 5234;
    activeUserCount.value = 18426;
    onlineUserGrowth.value = '+1245';
    activeUserGrowth.value = '+3842';
  }

  // 更新趋势图表
  if (onlineChartRef.value && activeChartRef.value) {
    const onlineChart = echarts.getInstanceByDom(onlineChartRef.value);
    const activeChart = echarts.getInstanceByDom(activeChartRef.value);

    if (onlineChart) onlineChart.setOption(getChartOptions('在线用户', '#1890FF'));
    if (activeChart) activeChart.setOption(getChartOptions('活跃用户', '#2FC25B'));
  }
}

// 获取趋势图配置
function getChartOptions(title: string, color: string) {
  // 根据时间范围生成不同的x轴标签和数据
  const { xAxisData, onlineData, activeData } = generateChartData();

  return {
    title: { show: false },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#eee',
      borderWidth: 1,
      textStyle: { color: '#333' },
      formatter: (params: any) => {
        const param = params[0];
        return `<div style="font-size:12px">${param.name}</div>
                <div style="color:${param.color};font-size:14px;font-weight:bold">${param.value}</div>`;
      },
    },
    grid: {
      left: '0',
      right: '0',
      top: '5%',
      bottom: '0',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisTick: { show: false },
      axisLine: { show: false },
      axisLabel: {
        show: true,
        color: '#999',
        fontSize: 10,
        interval: 'auto',
        rotate: timeRange.value === 'month' ? 45 : 0,
      },
    },
    yAxis: { show: false },
    series: [
      {
        name: title,
        type: 'line',
        data: title === '在线用户' ? onlineData : activeData,
        symbol: 'circle',
        symbolSize: 4,
        showSymbol: false,
        hoverAnimation: true,
        itemStyle: { color: color },
        lineStyle: {
          width: 2,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: color },
              { offset: 1, color: 'rgba(255, 255, 255, 0)' },
            ],
          },
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: `${color}30` },
              { offset: 1, color: 'rgba(255, 255, 255, 0)' },
            ],
          },
        },
      },
    ],
  };
}

// 生成趋势图数据
function generateChartData() {
  const isDay = timeRange.value === 'day';
  const isWeek = timeRange.value === 'week';

  if (isDay) {
    // 今日数据（小时为单位）
    return {
      xAxisData: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'],
      onlineData: [65, 42, 51, 98, 156, 189, 172, 186],
      activeData: [120, 85, 130, 320, 580, 720, 810, 842],
    };
  } else if (isWeek) {
    // 本周数据（天为单位）
    return {
      xAxisData: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      onlineData: [850, 920, 1050, 980, 1100, 1230, 1254],
      activeData: [4200, 4500, 5100, 4800, 5300, 5700, 5842],
    };
  } else {
    // 本月数据（简化为5个点）
    return {
      xAxisData: ['1日', '7日', '14日', '21日', '28日'],
      onlineData: [3200, 3800, 4500, 4900, 5234],
      activeData: [12500, 14200, 16800, 17900, 18426],
    };
  }
}

// 获取饼图配置
function getPieChartOptions() {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      padding: 8,
      backgroundColor: '#fff',
      borderColor: '#e9e9e9',
      textStyle: { color: '#333' },
    },
    series: [
      {
        name: '用户来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 8,
          borderWidth: 2,
          borderColor: '#fff',
        },
        label: {
          show: false,
          position: 'outside',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold',
          },
        },
        data: sourceData.value.map((item) => ({
          name: item.name,
          value: parseInt(item.value.replace('%', '')),
          itemStyle: { color: item.color },
        })),
      },
    ],
  };
}

// 模拟导出功能
const handleExport = () => {
  console.log('导出用户来源数据:', sourceData.value);
  // 实际可调用导出接口或生成CSV
};
</script>

<style scoped>
/* 图表容器样式 */
[ref^='onlineChartRef'],
[ref^='activeChartRef'],
[ref^='pieChartRef'] {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  background-color: #f9fafb;
}

/* 响应式布局调整 */
@media (max-width: 1024px) {
  .md\:flex-row {
    flex-direction: column;
  }
}
</style>